{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<center>\n",
    "<img src=\"../../img/ods_stickers.jpg\" />\n",
    "    \n",
    "## [mlcourse.ai](https://mlcourse.ai) – Open Machine Learning Course \n",
    "### <center> Author: I_Kalininskii, Kiavip\n",
    "    \n",
    "## <center> Tutorial\n",
    "### <center> \"Constructing simple Chatbot using **spaCy** - Industrial-Strength Natural Language Processing\"\n",
    " "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This tutorial based on works of Shirish Kadam (Adam https://shirishkadam.com/tag/spacy/ ) and Parul Pandey (Robo https://medium.com/analytics-vidhya/building-a-simple-chatbot-in-python-using-nltk-7c8c8215ac6e). With respect to the authors, code used only to show spaCy in action."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the words of *Matthew Honnibal* (author of spaCy);\n",
    "\n",
    "” There’s a real philosophical difference between spaCy and NLTK. spaCy is written to help you get things done. It’s minimal and opinionated. We want to provide you with exactly one way to do it — the right way. In contrast, NLTK was created to support education. Most of what’s there is for demo purposes, to help students explore ideas. spaCy provides very fast and accurate syntactic analysis (the fastest of any library released), and also offers named entity recognition and ready access to word vectors. You can use the default word vectors, or replace them with any you have.\n",
    "\n",
    "What really sets it apart, though, is the API. spaCy is the only library that has all of these features together, and allows you to easily hop between these levels of representation. Here’s an example of how that helps. Tutorial: Search Reddit for comments about Google doing something . spaCy also ensures that the annotations are always aligned to the original string, so you can easily print mark-up: Tutorial: Mark all adverbs, particularly for verbs of speech . “\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To install spaCy you may use simple commands:\n",
    "\n",
    "**pip install --trusted-host pypi.org spacy**\n",
    "\n",
    "or, maybe:\n",
    "\n",
    "**pip install --trusted-host pypi.org -U spacy**\n",
    "\n",
    "And then you need to download core and some models, which you will be able to use in your projects:\n",
    "\n",
    "**python -m spacy download en**\n",
    "\n",
    "**python -m spacy download en_core_web_sm**\n",
    "\n",
    "**python -m spacy download en_core_web_md**\n",
    "\n",
    "**python -m spacy download en_core_web_lg**\n",
    "\n",
    "**python -m spacy download en_vectors_web_lg**\n",
    "\n",
    "First *(\"en\")* is a basic module to work with English language. \n",
    "\n",
    "Second *(\"en_core_web_sm\")* is an english multi-task Convolucional Neural Network (CNN) trained on OntoNotes, with GloVe vectors trained on Common Crawl. Assigns word vectors, context-specific token vectors, POS tags, dependency parse and named entities. This one I shall use.\n",
    "\n",
    "Third *(\"en_core_web_md\")*  is an english multi-task CNN trained on OntoNotes, with GloVe vectors trained on Common Crawl. Assigns word vectors, context-specific token vectors, POS tags, dependency parse and named entities. This one brings powerful extensions.\n",
    "\n",
    "Fourth *(\"en_core_web_lg\")* is an English multi-task CNN trained on OntoNotes, with GloVe vectors trained on Common Crawl. Assigns word vectors, context-specific token vectors, POS tags, dependency parse and named entities. This model is really huge and complicated.\n",
    "\n",
    "Fifth *(\"en_vectors_web_lg\")* is a 300-dimensional word vectors trained on Common Crawl with GloVe. This model is especially useful when it came to deep meaning of words due to large number of vectors: more than a million!\n",
    "\n",
    "Of course, spaCy supports other languages: German, Spanish, Portuguese, French, Italian and Dutch. But I will use only English."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To show the way spaCy deals with Natural Language Processing, I'll implement simple chatbot. First, import spaCy to your notebook and load preferred model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "\n",
    "import spacy\n",
    "from spacy.matcher import PhraseMatcher"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nlp = spacy.load(\"en_core_web_sm\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now I'll introduce some text to spaCy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text = (\n",
    "    u\"Tutorials must be written in English.\"\n",
    "    u\"As for programming language, only Python is allowed.\"\n",
    ")\n",
    "doc = nlp(text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Just to show you some basics, i'll perform two simple loops. First, split by sentences, which are spaCy's Span objects:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for sent in doc.sents:\n",
    "    print(sent.text, sent.lemma_)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then, split by words, which are spaCy's **Token** objects "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for token in doc:\n",
    "    print(\n",
    "        token.i,\n",
    "        token.text,\n",
    "        token.lemma_,\n",
    "        token.tag_,\n",
    "        token.pos_,\n",
    "        token.dep_,\n",
    "        token.head.text,\n",
    "        token.head.pos_,\n",
    "        [child for child in token.children],\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are many important objects, but these are essentials) You may see, sentences are splitted correctly. Words are tokenized, marked as fine-grained part-of-speech *(token.tag_)*, coarse-grained part-of-speech *(token.pos_)* and syntactic dependency relation *(token.dep_)*. They can have head token and child tokens, which are Token objects too!\n",
    "\n",
    "spaCy has useful visualisation module displaCy. It can visualise dependency tree of a sentence, highlight some entitities and many more."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now I'll implement some base functions.\n",
    "\n",
    "I need to find complements: there will be use of some dependencies:\n",
    "\n",
    "*xcomp*: An open clausal complement (xcomp) of a verb or an adjective is a predicative or clausal complement without its own subject.\n",
    "\n",
    "*amod*: An adjectival modifier of a noun is any adjectival phrase that serves to modify the meaning of the noun.\n",
    "\n",
    "*ccomp*: A clausal complement of a verb or adjective is a dependent clause which is a core argument. That is, it functions like an object of the verb, or adjective.\n",
    "\n",
    "*acomp*: An adjectival complement of a verb is an adjectival phrase which functions as the complement"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_root_phrase(token, keywords):\n",
    "    \"\"\"\n",
    "    Get all complements of a verb\n",
    "    \"\"\"\n",
    "\n",
    "    for child in token.children:\n",
    "        if child.dep_ == any([\"acomp\", \"xcomp\", \"ccomp\"]):\n",
    "            keywords.append(child.lemma_)\n",
    "    return keywords"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_adj_phrase(token, token_text):\n",
    "    \"\"\"\n",
    "    To fetch all the adjectives describing the noun\n",
    "    \"\"\"\n",
    "\n",
    "    for child in token.children:\n",
    "        if (\n",
    "            child.dep_ == \"amod\" or child.dep_ == \"acomp\" or child.dep_ == \"ccomp\"\n",
    "        ):  # not for how many\n",
    "            if child.text != \"much\" and child.text != \"many\":\n",
    "                token_text = child.lemma_ + \" \" + token_text\n",
    "    return token_text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_compound_nouns(en_doc, token, token_text):\n",
    "    \"\"\"\n",
    "    Recursively find the left and right compound nouns\n",
    "    \"\"\"\n",
    "\n",
    "    parent_token = token\n",
    "    # If previous token is a compound noun\n",
    "    while token.i > 0 and en_doc[token.i - 1].dep_ == \"compound\":\n",
    "        token_text = en_doc[token.i - 1].text + \" \" + token_text\n",
    "        token = en_doc[token.i - 1]\n",
    "        # if the compound noun has any adjective modifier\n",
    "        token_text = get_adj_phrase(token, token_text)\n",
    "\n",
    "    token = parent_token\n",
    "\n",
    "    # If next token is a compound noun\n",
    "    while token.i < len(en_doc) - 1 and en_doc[token.i + 1].dep_ == \"compound\":\n",
    "        token_text = token_text + \" \" + en_doc[token.i + 1].text\n",
    "        token = en_doc[token.i + 1]\n",
    "        # if the compound noun has any adjective modifier\n",
    "        token_text = get_adj_phrase(token, token_text)\n",
    "\n",
    "    # NOTE: Can token.shape_ == Xxxx... or XXXX... token.ent_iob_ help us here ...?\n",
    "\n",
    "    return token_text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_noun_chunk(sentence, en_doc, keywords):\n",
    "    \"\"\"\n",
    "    Parse given sentense and return keywords incrementally\n",
    "    \"\"\"\n",
    "    root_word = \"\"\n",
    "\n",
    "    for token in sentence:\n",
    "\n",
    "        # If is Noun/Proper Noun, be it Singular or Plural\n",
    "        if (\n",
    "            token.tag_ == \"NN\"\n",
    "            or token.tag_ == \"NNP\"\n",
    "            or token.tag_ == \"NNPS\"\n",
    "            or token.tag_ == \"NNS\"\n",
    "        ):\n",
    "            # If the Noun itself is not a compound Noun then we can find its compound Nouns\n",
    "            if token.dep_ != \"compound\":\n",
    "                token_text = get_compound_nouns(en_doc, token, token.text)\n",
    "                keywords.append(token_text)\n",
    "\n",
    "        if token.tag_ == \"JJ\" and token.dep_ == \"attr\":\n",
    "            token_text = get_compound_nouns(en_doc, token, token.text)\n",
    "            token_text = get_adj_phrase(token, token_text)\n",
    "            keywords.append(token_text)\n",
    "\n",
    "        # If is a Cardinal Number & dependency is numeric modifier\n",
    "        # nummod : A numeric modifier of a noun is any number phrase that\n",
    "        #          serves to modify the meaning of the noun with a quantity.\n",
    "        if token.dep_ == \"nummod\" or token.tag_ == \"CD\":\n",
    "            token_text = token.text\n",
    "\n",
    "            if token.i > 0:\n",
    "                # If previous token is Adjective, the adjective is liked with the cardinal number\n",
    "                if en_doc[token.i - 1].tag_ == \"JJ\":\n",
    "                    token_text = en_doc[token.i - 1].text + \" \" + token.text\n",
    "\n",
    "            if token.i < len(en_doc) - 1:\n",
    "                # If next token is Adjective\n",
    "                if en_doc[token.i + 1].tag_ == \"JJ\":\n",
    "                    token_text = token.text + \" \" + en_doc[token.i + 1].text\n",
    "\n",
    "            keywords.append(token_text)\n",
    "\n",
    "        # Extracts the root word of sentence\n",
    "        if token.dep_ == \"ROOT\":\n",
    "            root_word = token.lemma_\n",
    "            keywords = get_root_phrase(token, keywords)\n",
    "\n",
    "    return root_word, keywords"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**extract_features**(*sentence_type, en_doc*) is the main procedure of sentence parsing. sentence_type will be used lately to determine, if it is question, argument, command or another construction."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def extract_features(sentence_type, en_doc):\n",
    "    \"\"\"\n",
    "    Extract keywords, sentence_type argument isn't implemented yet(\n",
    "    \"\"\"\n",
    "\n",
    "    keywords = []\n",
    "\n",
    "    for sentence in en_doc.sents:\n",
    "        root, keywords = get_noun_chunk(sentence, en_doc, keywords)\n",
    "        keywords.append(root)\n",
    "\n",
    "    return keywords"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Parse given sentence."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_sentence_doc(sentence):\n",
    "    sentence_doc = nlp(u\"\" + sentence)\n",
    "    return sentence_doc"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It's not implemented, but bot should understand, if it is a question or a statement, or, maybe, useless text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def classify_sentence(sentence_doc):\n",
    "    return None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sentence processing chain."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def process_sentence(sentence):\n",
    "    \"\"\"\n",
    "    get strait object \n",
    "    \"\"\"\n",
    "\n",
    "    sentence_doc = get_sentence_doc(sentence)\n",
    "    sentence_class = classify_sentence(sentence_doc)\n",
    "    sentence_keywords = extract_features(sentence_class, sentence_doc)\n",
    "    matcher_map = construct_matcher(sentence_keywords, sentence_doc)\n",
    "    return matcher_map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class MatcherMap:\n",
    "\n",
    "    \"\"\"\n",
    "    This is class is created to build spaCy Matcher or PraseMatcher\n",
    "    [0] - Features\n",
    "    [1] - Conjunctions (nested list with the conjunct and coordinating conjunction)\n",
    "    [2] - Negations\n",
    "    [3] - Markers\n",
    "    \"\"\"\n",
    "\n",
    "    __constructed_matcher__ = [None] * 4\n",
    "    coordinating_conjuncts = []\n",
    "\n",
    "    def __init__(self, ip_matcher=None):\n",
    "        if ip_matcher is not None and len(ip_matcher) == 4:\n",
    "            self.__constructed_matchery__ = ip_matcher\n",
    "\n",
    "    def add_features(self, feature_list):\n",
    "        self.__constructed_matcher__[0] = feature_list\n",
    "\n",
    "    def add_conjunctions(self, conjunction_list):\n",
    "        self.__constructed_matcher__[1] = conjunction_list\n",
    "\n",
    "    def add_coordinating_conjunct(self, c_conjunct):\n",
    "        self.coordinating_conjuncts.append(c_conjunct)\n",
    "\n",
    "    def add_negations(self, negation_list):\n",
    "        self.__constructed_matcher__[2] = negation_list\n",
    "\n",
    "    def add_markers(self, marker_list):\n",
    "        self.__constructed_matcher__[3] = marker_list\n",
    "\n",
    "    def get_constructed_qery(self):\n",
    "        return self.__constructed_matcher__\n",
    "\n",
    "    def get_features(self):\n",
    "        return self.__constructed_matcher__[0]\n",
    "\n",
    "    def get_conjunctions(self):\n",
    "        return self.__constructed_matcher__[1]\n",
    "\n",
    "    def get_negations(self):\n",
    "        return self.__constructed_matcher__[2]\n",
    "\n",
    "    def get_markers(self):\n",
    "        return self.__constructed_matcher__[3]\n",
    "\n",
    "    def __repr__(self):\n",
    "        return (\n",
    "            \"{Features: \" + str(self.__constructed_matcher__[0]) + \" ,\"\n",
    "            \"Conjunction: \" + str(self.__constructed_matcher__[1]) + \" ,\"\n",
    "            \"Negations: \" + str(self.__constructed_matcher__[2]) + \" ,\"\n",
    "            \"Marker: \" + str(self.__constructed_matcher__[3]) + \"}\"\n",
    "        )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_conjuncts(token):\n",
    "    \"\"\"\n",
    "    A conjunct is the relation between two elements connected by a coordinating conjunction, such as and, or, etc.\n",
    "     We treat conjunctions asymmetrically: The head of the relation is the first conjunct and all the other conjuncts\n",
    "      depend on it via the conj relation.\n",
    "    Coordinating Conjunction: and, or, but, yet, so, nor, for.\n",
    "    Correlative Conjunctions: either...or, whether...or, not only...but also\n",
    "    \"\"\"\n",
    "\n",
    "    parent = token.head\n",
    "    conj = [parent.text]\n",
    "\n",
    "    for child in parent.children:\n",
    "        if child.dep_ == \"conj\":\n",
    "            conj.append(child.text)\n",
    "\n",
    "    return conj"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This function constructs lists of features and relations for future Matchers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_matcher(sentence, feature_list):\n",
    "    \"\"\"\n",
    "    This function sequentially adds the query components to the structured query.\n",
    "    \"\"\"\n",
    "\n",
    "    matcher_map = MatcherMap()\n",
    "    matcher_map.add_features(feature_list)\n",
    "\n",
    "    conjunct_list = []\n",
    "    neg_list = []\n",
    "    mark_list = []\n",
    "\n",
    "    for token in sentence:\n",
    "\n",
    "        # cc: A cc is the relation between a conjunct and a preceding coordinating conjunction.\n",
    "        if token.dep_ == \"cc\":\n",
    "            conjunct_list.append(get_conjuncts(token))\n",
    "            conjunct_list.append(token.text)\n",
    "            matcher_map.add_coordinating_conjunct(token.text)\n",
    "\n",
    "        # neg: The negation modifier is the relation between a negation word and the word it modifies.\n",
    "        if token.dep_ == \"neg\":\n",
    "            if token.i > token.head.i:\n",
    "                neg_list.append([token.text, token.head.text])\n",
    "            else:\n",
    "                neg_list.append([token.head.text, token.text])\n",
    "\n",
    "        # mark: A marker is the word introducing a finite clause subordinate to another clause.\n",
    "        if token.dep_ == \"mark\":\n",
    "            if token.i > token.head.i:\n",
    "                mark_list.append([token.text, token.head.text])\n",
    "            else:\n",
    "                mark_list.append([token.head.text, token.text])\n",
    "\n",
    "    matcher_map.add_conjunctions(conjunct_list)\n",
    "    matcher_map.add_negations(neg_list)\n",
    "    matcher_map.add_markers(mark_list)\n",
    "\n",
    "    return matcher_map"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each sentence will be processed to the essential keywords and relations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def construct_matcher(features_list, en_doc):\n",
    "    matcher_constructed_obj = []\n",
    "\n",
    "    for sentence in en_doc.sents:\n",
    "        matcher_constructed_obj.append(get_matcher(sentence, features_list))\n",
    "\n",
    "    return matcher_constructed_obj"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**spaCy** features a rule-matching engine, **the Matcher**, that operates over tokens, similar to regular expressions. The rules can refer to token annotations (e.g. the **token** text or tag_, and flags (e.g. IS_PUNCT). The rule matcher also lets you pass in a custom callback to act on matches – for example, to merge entities and apply custom labels. You can also associate patterns with entity IDs, to allow some basic entity linking or disambiguation. To match large terminology lists, you can use the **PhraseMatcher**, which accepts **Doc** objects as match patterns.\n",
    "\n",
    "Here is **spaCy Rule-Based matcher** comes in action! Features should be added as rules. And, of course, **PhraseMatcher** and **Matcher** are versatile tools, so you can set them to do some complex searching. I can implement only simplest Matcher, because deadline is so close."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_answer(doc, features):\n",
    "    \"\"\"\n",
    "    process given text and find features\n",
    "    \"\"\"\n",
    "    nlp_features = []\n",
    "    answer_list = []\n",
    "    matcher = PhraseMatcher(nlp.vocab)\n",
    "\n",
    "    for f in features:\n",
    "        for word in f.get_features():\n",
    "            nlp_features.append(nlp(word))\n",
    "\n",
    "    matcher.add(\"LEMMA\", None, *nlp_features)\n",
    "    matches = matcher(doc)\n",
    "\n",
    "    for sent in doc.sents:\n",
    "        for match_id, m_start, m_end in matches:\n",
    "            if (sent.start <= m_end) & (sent.end >= m_start):\n",
    "                answer_list.append(sent.text)\n",
    "\n",
    "    return \"\".join(set(answer_list))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Function returning simple responce"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def response(user_response):\n",
    "    bot_response = \"{0}: \".format(bot_name)\n",
    "    features = process_sentence(user_response)\n",
    "    answer = get_answer(doc, features)\n",
    "    if (answer == None) | (answer == \"\"):\n",
    "        bot_response += \"I am sorry! I don't understand you\"\n",
    "        return bot_response\n",
    "    else:\n",
    "        bot_response = bot_response + answer\n",
    "        return bot_response"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Add some greetings for the bot to be polite"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "GREETING_INPUTS = (\n",
    "    \"hello\",\n",
    "    \"hi\",\n",
    "    \"greetings\",\n",
    "    \"sup\",\n",
    "    \"what's up\",\n",
    "    \"hey\",\n",
    ")\n",
    "GREETING_RESPONSES = [\n",
    "    \"hi\",\n",
    "    \"hey\",\n",
    "    \"*nods*\",\n",
    "    \"hi there\",\n",
    "    \"hello\",\n",
    "    \"I am glad! You are talking to me\",\n",
    "]\n",
    "bot_name = \"spaCy lil bot\"\n",
    "\n",
    "\n",
    "def greeting(sentence):\n",
    "\n",
    "    for word in sentence.split():\n",
    "        if word.lower() in GREETING_INPUTS:\n",
    "            return random.choice(GREETING_RESPONSES)\n",
    "            continue"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is the main loop. As you can see, this little bot can answer only a simple question, but is can grow to a smart assistant."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "flag = True\n",
    "print(\n",
    "    \"{0}: I will answer your questions about loaded text. If you want to exit, type Bye!\".format(\n",
    "        bot_name\n",
    "    )\n",
    ")\n",
    "while flag == True:\n",
    "    user_response = input()\n",
    "    user_response_lwr = user_response.lower()\n",
    "    if user_response_lwr != \"bye\":\n",
    "        if user_response_lwr == \"thanks\" or user_response_lwr == \"thank you\":\n",
    "            flag = False\n",
    "            print(\"{0}: You are welcome..\".format(bot_name))\n",
    "        else:\n",
    "            if greeting(user_response_lwr) != None:\n",
    "                print(\"{0}: \".format(bot_name) + greeting(user_response_lwr))\n",
    "            else:\n",
    "                print(response(user_response))\n",
    "    else:\n",
    "        flag = False\n",
    "        print(\"{0}: Bye! don't forget to upvote me..\".format(bot_name))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Just load some big model and you can predict similariries! Anyhow, it may or may not help you. \n",
    "\n",
    "**spaCy** ready to accept almost any word2vec sets to enhance it's possibilities."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nlp_lg = spacy.load(\"en_core_web_lg\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_related(word):\n",
    "    filtered_words = [\n",
    "        w for w in word.vocab if w.is_lower == word.is_lower and w.prob >= -15\n",
    "    ]\n",
    "    similarity = sorted(filtered_words, key=lambda w: word.similarity(w), reverse=True)\n",
    "    return similarity[1:11]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print([w.lower_ for w in get_related(nlp_lg.vocab[u\"Russian\"])])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you or me provide little bot with additional knowledge and algorithms, it can works with maps, construct schedule or read the books for you. This one can be the base of speech-recognition engine. Vectors and similarity checks may enhance search and provide nearly endless conversational possibilities!"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
